from flask import Flask
from app.config import config
from app.admin import site, users, auth
from app.cli import register_cli
from app.extensions import db, migrate, login_manager, csrf
from app.filter import register_filter
from app.tasks import baidu
import os


def create_app(config_class=None):
    if config_class is None:
        config_class = os.getenv('FLASK_CONFIG', 'development')
    app = Flask(__name__)
    app.config.from_object(config[config_class])

    register_cli(app)
    register_buleprints(app)
    register_extensions(app)
    register_filter(app)

    return app


# 注册蓝本
def register_buleprints(app):
    # frontend
    app.register_blueprint(site.bp)
    app.register_blueprint(users.bp, url_prefix='/users')
    app.register_blueprint(auth.bp, url_prefix='/auth')


# 注册扩展
def register_extensions(app):
    # 注册jinja的do方法
    app.jinja_env.add_extension('jinja2.ext.do')

    db.init_app(app)
    migrate.init_app(app, db)
    csrf.init_app(app)
    login_manager.init_app(app)
